package org.guohao.mockdata.utils;

import com.google.common.util.concurrent.MoreExecutors;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executor;
import org.guohao.mockdata.constant.ManagerType;
import org.guohao.mockdata.controller.HomeController;
import org.guohao.mockdata.entity.DBConnectEntity;
import org.guohao.mockdata.log.LoggingService;

/**
 * Manages all the DataManagers of Everest and registers new ones.
 * Registers Everest's default SQLiteManager automatically.
 */
public class SyncManager {
    private static HashMap<ManagerType, DataManager> managers;
    private static HomeController homeController;
    private static Executor executor = MoreExecutors.directExecutor();
    private static ConnectSaver connectSaver;

    /**
     * @param homeController - to add a HistoryItem by invoking addHistoryItem()
     */
    public SyncManager(HomeController homeController) {
        SyncManager.homeController = homeController;
        managers = new HashMap<>();
        connectSaver = new ConnectSaver();

        // Registering the default
        try {
            registerManager(new SQLiteManager());
        } catch (Exception e) {
            System.out.println("SQLite Manager already exists: Nope, will never happen.");
        }
    }
    public void saveConnectSetting(DBConnectEntity dbConnectInfo) {
        connectSaver.dbConnectInfo = dbConnectInfo;
        executor.execute(connectSaver);
        homeController.addConnectListItem(dbConnectInfo);
    }

    /**
     * Retrieves the history from the configured source.
     *
     * @return A list of all the requests
     */
    public List<DBConnectEntity> getDBList() {
        List<DBConnectEntity> history = null;
        try {
            history = managers.get(ManagerType.SQLITE).getDBList();
        } catch (Exception e) {
            LoggingService.logSevere("History could not be fetched.", e);
        }
        return history;
    }

    /**
     * Registers a new DataManager to be used for syncing Everest's data
     * at various sources.
     */
    public void registerManager(DataManager newManager){
        if (!managers.containsKey(newManager.getIdentifier()))
            managers.put(newManager.getIdentifier(), newManager);

    }

    private static class ConnectSaver implements Runnable {
        private DBConnectEntity dbConnectInfo;

        @Override
        public void run() {
            try {
                managers.get(ManagerType.SQLITE).saveConnectSetting(dbConnectInfo);
            } catch (Exception e) {
                LoggingService.logSevere("Could not save connect.", e);
            }
        }
    }
}
